package com.developtools.actions;

import com.developtools.doc.DocumentManager;
import com.developtools.model.ClassApiInfo;
import com.developtools.utils.ApiUtils;
import com.developtools.utils.NotificationUtils;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.DefaultLogger;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * @author liujun
 */
public class MarkdownAction extends AnAction {

    private static final Logger logger = Logger.getInstance(MarkdownAction.class);

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();

        FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(false, true, false, false, false, false);
        VirtualFile virtualFile = FileChooser.chooseFile(fileChooserDescriptor, project, null);
        if (Objects.isNull(virtualFile)) {
            return;
        }

        String canonicalPath = virtualFile.getCanonicalPath();
        if (StringUtils.isBlank(canonicalPath)) {
            return;
        }
        logger.info("Select file " + canonicalPath);
        File file = new File(canonicalPath);
        List<ClassApiInfo> classApiInfos = ApiUtils.getApiForModule(project);

        Task.Backgroundable markdownTask = new Task.Backgroundable(project, "Markdown") {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {

                DocumentManager instance = DocumentManager.getInstance();
                instance.build("markdown", file, classApiInfos);
                logger.info("Generate success!");
            }

            @Override
            public void onSuccess(){
                NotificationUtils notificationUtils = NotificationUtils.getInstance(project);
                notificationUtils.send("Success","生成成功！");
                logger.info("Build Success!");
            }
        };

        ProgressManager instance = ProgressManager.getInstance();
        instance.run(markdownTask);

    }
}
